<script setup>
import {onMounted, ref} from 'vue';
import { User, Setting, Discount, Link } from "@element-plus/icons-vue";
import SecuritySettings from "@/views/SecuritySettings.vue";
import SubmitCertification from "@/views/SubmitCertification.vue";
import Info from "@/views/Info.vue";
import axios from 'axios'; // 引入 axios 进行后端交互
import defAva from '@/assets/头像.jpg'

const currentComponent = ref(Info); // 当前动态组件
const showAvatarDialog = ref(false); // 控制更换头像弹窗的显示
const uploadedImage = ref('/file/user/default.jpg'); // 默认头像路径
const previewImage = ref(''); // 存储头像预览路径
const uploadError = ref(''); // 存储上传错误信息
const uploadSuccessMessage = ref(''); // 上传成功提示

// 模拟用户 ID（根据实际业务动态设置）
const userId = ref(1); // 用户 ID

// 菜单选择逻辑
function handleMenuSelect(index) {
  switch (index) {
    case '3':
      currentComponent.value = SecuritySettings;
      break;
    case '4':
      currentComponent.value = SubmitCertification;
      break;
    case '1':
      currentComponent.value = Info;
      break;
    default:
      currentComponent.value = null;
  }
}

// 获取用户头像路径
async function fetchAvatar() {
  try {
    const response = await axios.get('/api/User/getUserById', { params: { id: userId.value } });
    console.log(response.data.data)
    if (response.data.data && response.data.data.picture) {
      // 替换反斜杠为正斜杠，确保路径标准化
      const picture = response.data.data.picture.replace(/\\/g, '/'); // 替换反斜杠为正斜杠
      uploadedImage.value = `http://localhost:8080/${picture}`;
    } else {
      uploadedImage.value = '@/assets/头像.jpg'; // 默认头像
    }
  } catch (error) {
    console.error('获取头像失败:', error);
    uploadedImage.value = '@/assets/头像.jpg'; // 默认头像
  }

}

// 上传图片后的回调
async function handleAvatarUpload(event) {

  const file = event.target.files[0];
  console.log(file)
  if (!file) return;

  // 文件大小校验
  if (file.size > 10 * 1024 * 1024) { // 10MB
    uploadError.value = '文件大小不能超过10MB！';
    return;
  }

  // 文件格式校验
  const validFormats = ['image/jpeg', 'image/png', 'image/gif'];
  if (!validFormats.includes(file.type)) {
    uploadError.value = '仅支持 JPG, PNG, GIF 格式！';
    return;
  }

  // 预览显示
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.value = e.target.result;
  };
  reader.readAsDataURL(file);

  // 使用 FormData 进行上传
  const formData = new FormData();
  formData.append('avatar', file);
  formData.append('id', userId.value); // 传递用户 ID

  try {
    const response = await axios.put('/api/User/updateAvatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });

    if (response.data && response.data.avatarUrl) {
      uploadedImage.value = response.data.avatarUrl.replace(/\\/g, '/'); // 更新显示新头像
      uploadSuccessMessage.value = '上传成功';
      uploadError.value = '';
    } else {
      uploadError.value = response.data.message || '上传失败，请重试！';
    }
  } catch (error) {
    uploadError.value = `上传失败: ${error.response?.data?.message || '未知错误'}`;
  }
}

// 确定上传
async function confirmAvatarUpload() {
  if (previewImage.value) {
    uploadedImage.value = previewImage.value; // 提交更新显示的头像
    uploadSuccessMessage.value = '头像已提交成功！';
    showAvatarDialog.value = false; // 关闭对话框
    fetchAvatar()
  } else {
    uploadError.value = '请上传有效的头像图片！';
  }
}


onMounted(() => {
  // 页面加载时获取用户头像
  fetchAvatar();
})
</script>

<template>
  <el-main :style="{ weight: '1200px'}">
    <el-row :style="{ marginRight: '20px'}">
      <!-- 左侧菜单栏 -->
      <el-col :span="8">
        <el-card :body-style="{ padding: '0px' }" class="box-card">
          <!-- 美化头像区域 -->
          <div
            class="avatar-container"
            @click="showAvatarDialog = true"
          >
            <img
              :src="uploadedImage"
              class="avatar-image"
              alt="头像"
            />
            <div class="avatar-overlay">
              修改头像
            </div>
          </div>
          <div class="user-info">
            <span class="user-name">游客</span>
            <span class="user-role">学生</span>
          </div>
          <div class="title-content">
            <span>账号管理</span>
          </div>
          <div>
            <el-col>
              <el-menu
                default-active="1"
                @select="handleMenuSelect">
                <el-menu-item index="1">
                  <div class="grid-content">
                    <span><el-icon><User /></el-icon> 基本信息</span>
                  </div>
                </el-menu-item>
                <el-menu-item index="4">
                  <div class="grid-content">
                    <span><el-icon><Discount /></el-icon> 认证信息</span>
                  </div>
                </el-menu-item>
                <el-menu-item index="3">
                  <div class="grid-content">
                    <span><el-icon><Setting /></el-icon> 安全设置</span>
                  </div>
                </el-menu-item>
                <!--                <el-menu-item index="4">-->
                <!--                  <div class="grid-content">-->
                <!--                    <span><el-icon><Link /></el-icon> 绑定登录账号</span>-->
                <!--                  </div>-->
                <!--                </el-menu-item>-->
              </el-menu>
            </el-col>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧动态组件 -->
      <el-col :span="16">
        <component :is="currentComponent"></component>
      </el-col>
    </el-row>

    <!-- 更换头像弹窗 -->
    <el-dialog title="上传头像" v-model="showAvatarDialog" width="600px">
      <div style="display: flex; justify-content: space-between;">
        <!-- 上传区域 -->
        <div style="width: 60%; padding-right: 20px;">
          <div style="border: 1px dashed #d9d9d9; padding: 20px; text-align: center;">
            <input
              type="file"
              accept="image/*"
              style="display: none;"
              id="avatar-upload"
              @change="handleAvatarUpload"
            />
            <label for="avatar-upload" style="cursor: pointer;">
              <div>点击上传</div>
              <div style="font-size: 12px; color: #909399;">仅支持 JPG, GIF, PNG，且文件小于 10M</div>
            </label>
          </div>
        </div>

        <!-- 预览区域 -->
        <div style="width: 35%; text-align: center;">
          <div style="margin-bottom: 10px;">头像预览</div>
          <img
            :src="previewImage || '/file/user/default.jpg'"
            alt="头像预览"
            style="width: 100px; height: 100px; border-radius: 50%; border: 1px solid #d9d9d9;"
          />
        </div>
      </div>
      <div v-if="uploadError" style="color: red; text-align: center; margin-top: 10px;">
        {{ uploadError }}
      </div>
      <div v-if="uploadSuccessMessage" style="color: green; text-align: center; margin-top: 10px;">
        {{ uploadSuccessMessage }}
      </div>
      <template #footer>
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAvatarUpload">确定</el-button>
      </template>
    </el-dialog>
  </el-main>
</template>

<style scoped>
/* 美化头像容器 */
.avatar-container {
  width: 120px;
  height: 120px;
  margin: 40px auto 10px;
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  border: 2px solid #d9d9d9;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.avatar-overlay {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 30%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  text-align: center;
  line-height: 30px;
  font-size: 14px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

/* 美化用户信息 */
.user-info {
  text-align: center;
  margin-top: 15px;
}

.user-name {
  display: block;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.user-role {
  display: block;
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.title-content {
  margin-top: 30px;
  font-size: 18px;
  margin-left: 50px;
  text-align: left;
}

.grid-content {
  font-size: 16px;
  margin-left: 50px;
  text-align: left;
}

.box-card {
  margin-left: 200px;
  width: 290px;
  height: 520px;
}
</style>
